//
//  LoginViewController.m
//  Calculated
//
//  Created by 张庆勇 on 2018/3/21.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "NSObject+LCAFRequest.h"
#import "LCAFRequestHost.h"

@implementation NSObject (LCAFRequest)

- (void)POSTWithHost:(NSString *)host
                path:(NSString *)path
               param:(NSDictionary *)param
               cache:(BOOL)isCache
           completed:(LCSuccessBlock)completed
               error:(LCFailBlock)errorBlock
{
    host = host.length>0 ? host : HOST_IP;
    [self afEnqueOperationForHost:host Path:path param:param method:@"POST" cache:isCache  completed:completed error:errorBlock];
}

- (void)GETWithHost:(NSString *)host
               path:(NSString *)path
              param:(NSDictionary *)param
              cache:(BOOL)isCache
          completed:(LCSuccessBlock)completed
              error:(LCFailBlock)errorBlock
{
    host = host.length>0 ? host : HOST_IP;
  

    [self afEnqueOperationForHost:host Path:path param:param method:@"GET" cache:isCache  completed:completed error:errorBlock];
}



- (void)upload:(NSString *)path parameters:(NSDictionary *)dic constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block progress:(void (^)(NSProgress * _Nonnull uploadProgress))progress success:(LCSuccessBlock)success failure:(LCFailBlock)failure
{
    LCAFRequestHost *networkHost = [LCAFRequestHost sharedLCAFRequestHost];
    networkHost.requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"text/html", @"text/plain", @"text/json", @"text/javascript", @"application/json"]];
    [networkHost.requestManager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    //formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
    [networkHost.requestManager POST:path parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
       block(formData);
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        progress(uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(task,responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"上传失败 %@", error);
        failure(task,error);
    }];
}
- (void)downloadWithUrl:(NSString *)url
            destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
      completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler
{
    NSURL *URL = [NSURL URLWithString:url];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        double progressValue = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        // 回到主队列刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showProgress:progressValue];
        });
        
    } destination:destination completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            if (completionHandler) {
                completionHandler(response,filePath,error);
            }
        });
    }];
    [downloadTask resume];
}

#pragma mark --- Privat Method



- (void)afEnqueOperationForHost:(NSString *)host
                           Path:(NSString *)path
                          param:(NSDictionary *)param
                         method:(NSString *)method
                          cache:(BOOL)isCache
                      completed:(LCSuccessBlock)completed
                          error:(LCFailBlock)errorBlock
{
    LCAFRequestHost *networkHost = [LCAFRequestHost sharedLCAFRequestHost];
    
    [networkHost afRequestWithUrlString:path method:method parameters:param cache:isCache successBlock:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       [LCAFRequestHost printObject:responseObject isReq:NO path:path];
        completed(task,responseObject);
        
    } failBlock:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorBlock(task,error);
        
    }];
    [self printUrlForPath:path
               andBaseUrl:[networkHost baseUrl]
               andParaDic:param];
}
+ (void)printObject:(NSDictionary *)dic isReq:(BOOL)isReq path:(NSString *)path{
    NSDictionary *json = @{};
    if (dic) {
        json = [dic mj_keyValues];
    }
    if (isReq) {
        
        NSLog(@"\n=====================\n请求参数\n==========================\n%@\n======================================================\n%@",json,path);
    }else {
        
        NSLog(@"\n=====================\n返回数据\n==========================\n%@\n=====================================================\n%@",json,path);
    }
}
- (void)printUrlForPath:(NSString *)path
             andBaseUrl:(NSString *)baseUrl
             andParaDic:(NSDictionary *)paramDic
{
    NSString *param = @"";
    for (int i=0; i<paramDic.count; i++) {
        NSString *key = [paramDic.allKeys objectAtIndex:i];
        param = [NSString stringWithFormat:@"%@&%@=%@", param, key, [paramDic objectForKey:key]];
    }
    if (param.length > 1) {
        NSLog(@"request url = %@?%@", [baseUrl stringByAppendingString:path], [param substringFromIndex:1]);
    }
    else {
        NSLog(@"request url = %@", [baseUrl stringByAppendingString:path]);
    }
}



- (void)cancelRequest{
    
}
@end

